<template>
    <div class="select-unit-page">
        <!-- Header with back arrow and title -->
        <div>
            <van-nav-bar :title="title" left-arrow @click-left="onClickLeft" />
        </div>

        <!-- Tabs -->
        <div>
            <tab :listData="tabList" keytype="employee" @tab-change="onTabChange"></tab>
        </div>

        <!-- Search Bar -->
        <div class="search-section">
            <van-search 
                v-model="searchValue" 
                shape="round" 
                :placeholder="searchPlaceholder"
                input-align="left"
                @input="onSearchInput"
            />
        </div>

        <!-- Breadcrumb Navigation -->
        <div class="breadcrumb-section" v-if="selectedEmployeeId != null">
            <div class="breadcrumb">
                <span 
                    v-for="(item, index) in breadcrumbList" 
                    :key="index"
                    class="breadcrumb-item"
                >
                    <span @click="clickBreadcrumb(item, index)" class="breadcrumb-text">{{ item }}</span>
                    <span v-if="index < breadcrumbList.length - 1" class="breadcrumb-separator"> > </span>
                </span>
            </div>
        </div>

        <!-- Content Area -->
        <div class="content-section" style="padding-top: 12px;">
            <!-- Employee List Section -->
            <div class="employee-list" v-if="activeTab === 'employee'" style="padding-top: 8px;">
                <div 
                    v-for="(employee, index) in filteredEmployees" 
                    :key="index"
                    class="employee-item"
                    :style="index === 0 ? 'margin-top: 4px;' : ''"
                    @click="selectEmployee(employee)"
                >
                    <van-radio 
                        :name="employee.memberId" 
                        v-model="selectedEmployeeId" 
                        :value="employee.memberId"
                        checked-color="#3772ff"
                        class="employee-radio"
                        @click.stop
                    ></van-radio>
                    
                    <div class="employee-icon">
                        <div class="icon-circle">
                            <van-icon name="bars" size="18" color="#fff" />
                        </div>
                    </div>
                    
                    <div class="employee-info">
                        <div class="employee-name">{{ employee.memberName }}</div>
                        <div class="employee-path">{{ employee.parentDeptNames }}</div>
                    </div>
                </div>
            </div>
            <div class="organization-list" v-if="activeTab=='employee'">
                       <div class="organization-section-label">组织</div>
                <organization-tree-item
                    v-for="(org, index) in filteredParentDeptList" 
                    :key="org.deptId || org.nodeId || index"
                    :org="org"
                    :level="0"
                    @select="selectOrganization"
                />
            </div>
            <!-- 内部组织-->
            <div class="organization-list" v-if="activeTab=='organization'">
                <div class="organization-section-label">组织</div>
                <van-radio-group
                    v-model="selectedOrganizationId"
                    @change="handleOrganizationRadioChange"
                >
                    <organization-tree-item
                        v-for="(org, index) in filteredOrganizationList" 
                        :key="org.nodeId || org.deptId || index"
                        :org="org"
                        :level="0"
                        :selectable="true"
                        @select="selectOrganization"
                    />
                </van-radio-group>
            </div>
            <!-- 外部主体 -->
            <div class="external-list" v-if="activeTab === 'external'" style="padding-top: 8px;">
                <div 
                    v-for="(subject, index) in filteredExternalList" 
                    :key="subject.subjectId || index"
                    class="employee-item"
                    :style="index === 0 ? 'margin-top: 4px;' : ''"
                    @click="selectSubject(subject)"
                >
                    <van-radio 
                        :name="subject.subjectId" 
                        v-model="selectedSubjectId" 
                        :value="subject.subjectId"
                        checked-color="#3772ff"
                        class="employee-radio"
                        @click.stop
                    ></van-radio>
                    
                    <div class="employee-icon">
                        <div class="icon-circle">
                            <van-icon name="friends-o" size="18" color="#fff" />
                        </div>
                    </div>
                    
                    <div class="employee-info">
                        <div class="employee-name">{{ subject.subjectName || subject.name }}</div>
                        <div class="employee-path">
                            <span v-if="subject.contactName">{{ subject.contactName }}</span>
                            <span v-if="subject.contactPhone">（{{ subject.contactPhone }}）</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Bottom Action Buttons -->
   
            <div class="btn-container">
            <div class="btnlist">
                <div class="btn-item" :class="{ activeBtn: type === 1 }" @click="onCancel">取消</div>
                <div class="btn-item" :class="{ activeBtn2: type === 2 }" @click="onConfirm">确认</div>
            </div>
        </div>
        
    </div>
</template>

<script>
import tab from './components/tab.vue'
import OrganizationTreeItem from './components/OrganizationTreeItem.vue'
import backMixin from '../../mixins/backMixin'

export default {
    name: 'selectUnit',
    mixins: [backMixin],
    components: {
        tab,
        OrganizationTreeItem
    },
    data() {
        return {
            type: 1,
            activeTab: 'employee',
            searchValue: '',
            mode:'',
            title:'请选择产权单位',
            selectedEmployeeId: null,
            tabList: [
                { name: '内部员工', key: 'employee' },
                { name: '内部组织', key: 'organization' },
                { name: '外部主体', key: 'external' }
            ],
            breadcrumbList: [],
            employees: [
                { id: 1, name: '张三客服主管', path: '集团/区域分公司/分公司/管理处/部门' },
                { id: 2, name: '张三客服主管', path: '集团/区域分公司/分公司/管理处/部门' },
                { id: 3, name: '张三客服主管', path: '集团/区域分公司/分公司/管理处/部门' },
                { id: 4, name: '张三客服主管', path: '集团/区域分公司/分公司/管理处/部门' },
                { id: 5, name: '张三客服主管', path: '集团/区域分公司/分公司/管理处/部门' },
                { id: 6, name: '张三客服主管', path: '集团/区域分公司/分公司/管理处/部门' }
            ],
            organizationList: [],
            parentDeptInfoList: [],
            subjectList:[],
            selectedOrganization: null,
            selectedOrganizationId: null,
            selectedSubjectId: null,
            selectedSubject: null
        }
    },
    computed: {
        searchPlaceholder() {
            if (this.activeTab === 'employee') {
                return '搜索员工姓名 / 手机号码'
            }
            if (this.activeTab === 'organization') {
                return '搜索组织名称'
            }
            if (this.activeTab === 'external') {
                return '搜索外部主体 / 联系方式'
            }
            return '搜索'
        },
        filteredEmployees() {
            if (this.activeTab !== 'employee') {
                return this.employees
            }
            const keyword = this.searchValue.trim().toLowerCase()
            if (!keyword) {
                return this.employees
            }
            return this.employees.filter((emp) => {
                const name = (emp.memberName || '').toLowerCase()
                const mobile = (emp.mobile || '').toLowerCase()
                const userAccount = (emp.userAccount || '').toLowerCase()
                return (
                    name.includes(keyword) ||
                    mobile.includes(keyword) ||
                    userAccount.includes(keyword)
                )
            })
        },
        filteredParentDeptList() {
            if (this.activeTab !== 'employee') {
                return this.parentDeptInfoList
            }
            return this.filterOrgTree(this.parentDeptInfoList, this.searchValue)
        },
        filteredOrganizationList() {
            if (this.activeTab !== 'organization') {
                return this.organizationList
            }
            return this.filterOrgTree(this.organizationList, this.searchValue)
        },
        filteredExternalList() {
            if (this.activeTab !== 'external') {
                return this.subjectList
            }
            const keyword = this.searchValue.trim().toLowerCase()
            if (!keyword) {
                return this.subjectList
            }
            return (this.subjectList || []).filter((subject) => {
                const name = (subject.subjectName || subject.name || '').toLowerCase()
                const contactName = (subject.contactName || '').toLowerCase()
                const phone = (subject.contactPhone || subject.contactTel || '').toLowerCase()
                return (
                    name.includes(keyword) ||
                    contactName.includes(keyword) ||
                    phone.includes(keyword)
                )
            })
        }
    },
    created(){
        this.clearSelections()
        this.handleRouteKey(this.$route.params.key)
        // 监听路由参数变化自动调用对应接口
        this.$watch(
            () => this.$route.params.key,
            (newKey, oldKey) => {
                if (newKey !== oldKey && typeof this.handleRouteKey === 'function') {
                    this.handleRouteKey(newKey)
                }
            }
        )
    },
    activated() {
        // 当组件从 keep-alive 恢复或路由返回时，清除之前的选择
        this.clearSelections()
        // 重新根据参数加载对应模式
        this.handleRouteKey(this.$route.params.key)
    },
    mounted() {
        this.clearSelections()
        this.getEmployees()
        this.getOrganizationTree()
        this.getsubjectList()
    },
    methods: {
        handleRouteKey(key) {
            this.mode = key;
            // 只处理移交单位，设置标题和占位文本
            if (key === 'yjdw') {
                this.title = '选择移交单位';
                this.placeholder = '搜索单位名称/分组';
                this.activeTab='organization'
                // 过滤掉key
                this.tabList = this.tabList.filter(item => item.key !== 'employee');
                console.log(this.tabList,'tablist')
            }
            if (key === 'cqdw') {
                this.title = '选择产权单位';
                this.placeholder = '搜索单位名称/分组';
                this.activeTab='organization'
                // 过滤掉key
                this.tabList = this.tabList.filter(item => item.key !== 'employee');
                console.log(this.tabList,'tablist')
            }
            if (key === 'dyqr') {
                this.title = '选择抵押权人';
                this.placeholder = '搜索人员名字/分组';
               // this.activeTab='organization'
                // 过滤掉key
              //  this.tabList = this.tabList.filter(item => item.key !== 'employee');
                console.log(this.tabList,'tablist')
            }
        },
      getEmployees(id) {
        let data = {
           orgId:id || sessionStorage.getItem('orgId')
        }
        this.$Geting(this.$api.getDeptMemberPosition,data).then(res => {
            console.log(res,'res')
            if(res.code == '0') {
                this.employees = res.data.memberInfos || []
                this.parentDeptInfoList = res.data.sonDeptInfos || []
            } else {
                this.$toast(res.message)
            }
        })
      },
      getsubjectList(){
   
        let data = {
            keywords:'',
            scopeName:'', // 外部主体使用范围
        }
        this.$Geting(this.$api.getsubject,data).then(res => {
            console.log(res,'res')
            if(res.code == '0') {
                this.subjectList = res.data || []
            } else {
                this.$toast(res.message)
            }
        })
      },
        filterOrgTree(list = [], keyword = '') {
            const lowerKeyword = keyword.trim().toLowerCase()
            if (!lowerKeyword) {
                return list
            }
            const traverse = (node) => {
                if (!node || typeof node !== 'object') {
                    return null
                }
                const name = this.getOrgName(node).toLowerCase()
                const childKey = this.getOrgChildKey(node)
                const children = childKey ? node[childKey] || [] : []
                const filteredChildren = children.map(traverse).filter(Boolean)
                const isMatch = name.includes(lowerKeyword)
                if (isMatch || filteredChildren.length > 0) {
                    const cloned = { ...node }
                    if (childKey) {
                        cloned[childKey] = filteredChildren
                    }
                    return cloned
                }
                return null
            }
            return (list || []).map(traverse).filter(Boolean)
        },
        getOrgName(org = {}) {
            return org.nodeName || org.name || org.deptName || ''
        },
        getOrgChildKey(org = {}) {
            if (org.childList) return 'childList'
            if (org.children) return 'children'
            if (org.sonDeptInfos) return 'sonDeptInfos'
            if (org.sonDeptInfoList) return 'sonDeptInfoList'
            return null
        },
        getOrgUniqueId(org = {}) {
            return org.nodeId || org.deptId || org.id || org.value || org.name
        },
        handleOrganizationRadioChange(id) {
            if (!id) {
                this.selectedOrganization = null
                this.selectedOrganizationId = null
                return
            }
            const target = this.findOrgById(id, this.organizationList)
            if (target) {
                this.selectedOrganizationId = id
                this.selectedOrganization = target
            }
        },
        findOrgById(id, list = []) {
            const strId = String(id)
            for (const node of list) {
                const nodeId = this.getOrgUniqueId(node)
                if (nodeId && String(nodeId) === strId) {
                    return node
                }
                const childKey = this.getOrgChildKey(node)
                if (childKey && node[childKey] && node[childKey].length) {
                    const found = this.findOrgById(id, node[childKey])
                    if (found) {
                        return found
                    }
                }
            }
            return null
        },
        onClickLeft() {
            this.$router.back()
        },
        onTabChange(tabKey) {
            this.activeTab = tabKey
            this.selectedOrganization = null
            this.searchValue = ''
            // 切换标签时处理面包屑
            if (tabKey === 'employee') {
                // 切换到员工标签时，如果有选中的员工，显示对应的面包屑
                if (this.selectedEmployeeId) {
                    const selectedEmployee = this.employees.find(emp => emp.memberId === this.selectedEmployeeId)
                    if (selectedEmployee && selectedEmployee.parentDeptNames) {
                        this.breadcrumbList = selectedEmployee.parentDeptNames.split('/').filter(item => item && item.trim())
                    } else {
                        this.breadcrumbList = []
                    }
                } else {
                    this.breadcrumbList = []
                }
            } else if (tabKey === 'external') {
                this.breadcrumbList = []
                this.selectedEmployeeId = null
                if (this.subjectList.length === 0) {
                    this.getsubjectList()
                }
            } else {
                // 切换到其他标签时重置面包屑
                this.breadcrumbList = []
                this.selectedEmployeeId = null
            }
            if (tabKey === 'organization' && this.organizationList.length === 0) {
                this.getOrganizationTree()
            }
        },
        onSearchInput(value) {
            this.searchValue = value
        },
        clickBreadcrumb(item, index) {
            // Handle breadcrumb click - navigate to that level
            this.breadcrumbList = this.breadcrumbList.slice(0, index + 1)
            console.log('Clicked breadcrumb:', item, index)
        },
        selectEmployee(employee) {
            this.selectedEmployeeId = employee.memberId
            // 根据员工的 parentDeptNames 更新面包屑
            if (employee.parentDeptNames) {
                // 将 parentDeptNames 按 "/" 分割成数组
                this.breadcrumbList = employee.parentDeptNames.split('/').filter(item => item && item.trim())
            } else {
                this.breadcrumbList = []
            }
        },
        selectSubject(subject) {
            this.selectedSubjectId = subject.subjectId || subject.id
            this.selectedSubject = subject
        },
        getOrganizationTree() {
            let data = {
                orgId: sessionStorage.getItem('orgId')
            }
            this.$Geting(this.$api.getorgTree, data).then(res => {
                console.log(res, '组织树数据')
                if (res.code == '0') {
                    // 处理树形数据，如果返回的是单个对象，转换为数组
                    if (res.data && res.data.treeData) {
                        this.organizationList = [res.data.treeData]
                    } else if (res.data && Array.isArray(res.data)) {
                        this.organizationList = res.data
                    } else if (res.data && res.data.childList) {
                        this.organizationList = res.data.childList
                    } else {
                        this.organizationList = []
                    }
                } else {
                    this.$toast(res.message)
                }
            }).catch(err => {
                console.error('获取组织树失败:', err)
                this.$toast('获取组织数据失败')
            })
        },
        selectOrganization(org) {

            this.selectedOrganization = org
            this.selectedOrganizationId = this.getOrgUniqueId(org)
            console.log('Selected organization:', org)
            if(org.deptId) {
                this.getEmployees(org.deptId)
            }
        },
        // 清除已选中的节点与相关 UI 显示（用于在进入页面时重置状态）
        clearSelections() {
            this.selectedEmployeeId = null
            this.selectedOrganization = null
            this.selectedOrganizationId = null
            this.selectedSubjectId = null
            this.selectedSubject = null
            this.breadcrumbList = []
            this.searchValue = ''
            // 保留 tabList 与 mode 等不变
        },
        onCancel() {
            this.type=1
            this.$router.back()
        },
        onConfirm() {
            if (this.activeTab === 'employee') {
                if (this.selectedEmployeeId) {
                    const selectedEmployee = this.employees.find(emp => emp.memberId === this.selectedEmployeeId)
                    console.log('Selected employee:', selectedEmployee)
                    // Emit event or handle confirmation
               //     this.$emit('confirm', selectedEmployee)
                    if(this.mode=='dyqr'){
                        let newArr ={
                            mortgagee:selectedEmployee.memberName
                        }
                        try {
                            this.$store.commit('assectData/setReturnData', newArr)
                        } catch (e) {
                            console.warn('Vuex commit setReturnData failed', e)
                        }
                        this.$router.back()
                    }
                    // You can navigate back or emit to parent
                 //   this.$router.back()
                } else {
                    this.$toast('请选择员工')
                }
            } else if (this.activeTab === 'organization') {
                if (this.selectedOrganization) {
                    console.log('Selected organization:', this.selectedOrganization)
                    if(this.mode=='yjdw'){
                        let newArr ={
                            unitId:this.selectedOrganization.nodeId,
                            unitName:this.selectedOrganization.nodeName
                        }
                        try {
                            this.$store.commit('assectData/setReturnData', newArr)
                        } catch (e) {
                            console.warn('Vuex commit setReturnData failed', e)
                        }
                        this.$router.back()
                    }
                    if(this.mode=='cqdw'){
                        let newArr ={
                            rightUnitId:this.selectedOrganization.nodeId,
                            rightUnitName:this.selectedOrganization.nodeName
                        }
                        try {
                            this.$store.commit('assectData/setReturnData', newArr)
                        } catch (e) {
                            console.warn('Vuex commit setReturnData failed', e)
                        }
                        this.$router.back()
                    }
                    
                    // Emit event or handle confirmation
                    //this.$emit('confirm', this.selectedOrganization)
                    // You can navigate back or emit to parent
                  //  this.$router.back()
                } else {
                    this.$toast('请选择组织')
                }
            } else if (this.activeTab === 'external') {
                if (this.selectedSubjectId) {
                    const selectedSubject = this.subjectList.find(subject => (subject.subjectId || subject.id) === this.selectedSubjectId)
                    console.log('Selected subject:', selectedSubject)
                    this.$emit('confirm', selectedSubject)
                    this.$router.back()
                } else {
                    this.$toast('请选择外部主体')
                }
            }
            this.type = 2
        }
    }
}
</script>

<style scoped lang="less">
.select-unit-page {
    background-color: #f9f9f9;
    min-height: 100vh;
    padding-bottom: 70px;
}

.search-section {
    width: 100%;
    padding: 10px 15px;
    background-color: #fff;
    box-sizing: border-box;
}

.breadcrumb-section {
    background-color: #fff;
    padding: 12px 15px;
    border-bottom: 1px solid #f0f0f0;
}

.breadcrumb {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    font-size: 14px;
}

.breadcrumb-item {
    display: inline-flex;
    align-items: center;
}

.breadcrumb-text {
    color: #333;
    cursor: pointer;
    
    &:hover {
        color: #3772ff;
    }
}

.breadcrumb-separator {
    color: #999;
    margin: 0 8px;
}

.content-section {
    background-color: #fff;
    margin-top: 10px;
}

.employee-list {
    padding: 0;
    max-height: 30vh;
    width: 95vw;
    margin: 0 auto;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    // align-items: center;
    //justify-content: center;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    background: #fff;
    border-radius: 8px;
    -webkit-overflow-scrolling: touch;
    touch-action: pan-y;
}
.external-list{
    padding: 0;
    max-height: 30vh;
    width: 95vw;
    margin: 0 auto;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    // align-items: center;
    //justify-content: center;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    background: #fff;
    border-radius: 8px;
    -webkit-overflow-scrolling: touch;
    touch-action: pan-y;
}
.employee-item {
    display: flex;
    align-items: center;
    padding: 15px 10px;
    border-bottom: 1px solid #f0f0f0;
    cursor: pointer;
    background-color: #fff;
    touch-action: manipulation;
    
    &:last-child {
        border-bottom: none;
    }
    
    &:active {
        background-color: #f9f9f9;
    }
}

.employee-radio {
    margin-right: 15px;
    flex-shrink: 0;
}

.employee-icon {
    margin-right: 12px;
    flex-shrink: 0;
}

.icon-circle {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background-color: #3772ff;
    display: flex;
    align-items: center;
    justify-content: center;
}

.employee-info {
    flex: 1;
    min-width: 0;
}

.employee-name {
    font-size: 15px;
    color: #333;
    margin-bottom: 6px;
    font-weight: 500;
}

.employee-path {
    font-size: 13px;
    color: #999;
    line-height: 1.4;
}

.organization-list {
    border-top: 8px solid #f9f9f9;
    padding: 0;
    width: 95vw;
    margin: 0 auto;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    // align-items: center;
    justify-content: center;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    background: #fff;
    border-radius: 8px;
    -webkit-overflow-scrolling: touch;
    touch-action: pan-y;
}

.organization-section-label {
    padding: 12px 15px;
    font-size: 14px;
    color: #666;
    background-color: #fff;
    border-bottom: 1px solid #f0f0f0;
}


.footer-buttons {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex;
    padding: 10px 15px;
    background-color: #fff;
    border-top: 1px solid #e0e0e0;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

.cancel-btn {
    flex: 1;
    height: 44px;
    margin-right: 10px;
    background-color: #fff;
    color: #3772ff;
    border: 1px solid #3772ff;
    border-radius: 4px;
}

.confirm-btn {
    flex: 1;
    height: 44px;
    border-radius: 4px;
}
.btn-container {
        position: absolute;
        bottom: 30px;
        left: 50%;
        transform: translateX(-50%);
        width: 100%;
        display: flex;
        justify-content: center;
        padding: 0 20px;
    }

    .btnlist {
        display: flex;
        border: 1px solid #3772ff;
        background-color: #3772ff;
        border-radius: 12.5px;
        width: 305px;
        overflow: hidden;
    }

    .btn-item {
        flex: 1;
        padding: 12px;
        text-align: center;
        color: #fff;
        font-size: 14px;
        cursor: pointer;
        transition: all 0.3s;
    }

    .activeBtn {
        border-radius: 12.5px 0 17.5px 12.5px;
        background-color: #fff;
        color: #000;
    }

    .activeBtn2 {
        border-radius: 0 12.5px 12.5px 17.5px;
        background-color: #fff;
        color: #000;
    }
</style>